﻿/*
 * RegExpress
 * 
 * Copyright (c) 2010, Daniel McGaughran
 * 
 * Licensed under the Apache Licence, Version 2.0 (the "Licence");
 * you may not use this file except in compliance with the Licence.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 * 
 */

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using RegExpressModel.Entities;


namespace RegExpressModel
{
	public class MultiMatchModel : BaseRegexModel
	{
		private List<SingleMatchCase> _matchCases;


		public MultiMatchModel() : base()
        {
			_matchCases = new List<SingleMatchCase>();
        }


		public List<SingleMatchCase> MatchCases
		{
			get { return _matchCases; }
			set
			{
				if(value != null && value.Count > 0)
				{
					_matchCases = value;
					ReIndex();
					ResetResults();
				}
			}
		}



		public SingleMatchCase AddMatchCase()
		{
			return AddMatchCase("");
		}



		public SingleMatchCase AddMatchCase(string input)
		{
			int caseIndex = _matchCases.Count;
			SingleMatchCase newCase = new SingleMatchCase()
			{
				Index = caseIndex,
				Input = input
			};

			_matchCases.Add(newCase);
			return newCase; 
		}



		public bool PerformMatch()
		{
			if(IsValid)
			{
				foreach (SingleMatchCase matchCase in _matchCases)
				{
					Match result = RegexObject.Match(matchCase.Input);
					matchCase.ResultStatus = result.Success ? MatchResultType.Matches : MatchResultType.NoMatch;
					matchCase.MatchResult = result;
				}

				return true;
			}

			return false;
		}


		public bool PerformMatch(int index)
		{
			if(IsValid && index >= 0 && index < _matchCases.Count)
			{
				SingleMatchCase matchCase = _matchCases[index];
				Match result = RegexObject.Match(matchCase.Input);
				matchCase.ResultStatus = result.Success ? MatchResultType.Matches : MatchResultType.NoMatch;
				matchCase.MatchResult = result;

				return true;
			}

			return false;
		}



		private void ReIndex()
		{
			int i = 0;
			foreach(SingleMatchCase matchCase in _matchCases)
			{
				matchCase.Index = i;
				i++;
			}
		}


		protected override void ResetResults()
		{
			foreach (SingleMatchCase matchCase in _matchCases)
				matchCase.Reset();
		}

	
	}
}
